#  This file is part of FlickFleck.
#  Copyright (C) 2008 Jyke Tapani Jokinen
#
#    FlickFleck is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    FlickFleck is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with FlickFleck.  If not, see <http://www.gnu.org/licenses/>.
#
import config
import ui
import os.path
from subprocess import Popen, PIPE
from fileops import quotepath

def eqlen( str ):
  if len(str) == 1:
    str = "0" + str
  return str

# -----------------------------------------------------------------------
# return ('<year>/<month>', <datename>') tuple based on files EXIF date
#
def newname( filename ):

  # --a no duplicate tags
  # -f force printing of tags even if values are not found
  # -n print values as numbers
  cmd = config.exiftool + " --a -f -fast -n -CreateDate " + \
      quotepath(filename)
  try:
    pipe = Popen(cmd, shell=True, stdout=PIPE)
    pipe.wait()

    # parse createdate values
    (str, data) = pipe.stdout.readline().split(':', 1)
  except:
    ui.ERR( "problem running exiftool (%s)" % filename )

  if str.strip().lower() != "create date":
	ui.ERR( "exiftool: createdate not found (%s)" % filename )

  try:
    (date,time) = data.strip().split(' ')
    (year,mon,day) = date.split(':')
    mon = eqlen( mon )
    day = eqlen( day )
    (hour,min,sec)   = time.split(':')
    hour = eqlen( hour )
    min  = eqlen( min )
    sec  = eqlen( sec )
  except:
    ui.ERR( "problem parsing EXIF date (%s)" % data)

  newdir  = year + os.path.sep + mon
  newname = "%s%s%s-%s%s%s" % (year,mon,day,hour,min,sec)
  return (newdir, newname)
